/** 下载文件 */
function downloadByBlob(url, name) {
  const image = new Image()
  image.setAttribute('crossOrigin', 'anonymous')
  image.src = url
  image.onload = () => {
    const canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    const ctx = canvas.getContext('2d')
    ctx.drawImage(image, 0, 0, image.width, image.height)
    canvas.toBlob((blob) => {
      const url = URL.createObjectURL(blob)
      download(url, name)
      // 用完释放URL对象
      URL.revokeObjectURL(url)
    })
  }
}
function download(href, name) {
  const eleLink = document.createElement('a')
  eleLink.download = name
  eleLink.href = href
  eleLink.click()
  eleLink.remove()
}

/** 判断是否图片类型文件 */
const isImageType = (file) => {
  const type = getFileType(file)
  if (type.includes('image/')) {
    return true
  }
  return false
}

/** 获取文件类型图标 */
const getIconByFileType = (file) => {
  const type = getFileType(file)
  if (type.includes('image/')) {
    return 'jpg'
  }
  if (type === 'application/msword') {
    return 'doc'
  }
  if (type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
    return 'doc'
  }
  if (type === 'application/vnd.ms-excel') {
    return 'xls'
  }
  if (type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
    return 'xls'
  }
  if (type === 'application/vnd.ms-powerpoint') {
    return 'ppt'
  }
  if (type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
    return 'ppt'
  }
  if (type === 'application/x-zip-compressed') {
    return 'zip'
  }
  if (type === 'application/octet-stream') {
    return 'zip'
  }
  return 'unknown'
}
/** 去文件列表中文件类型 */
const getFileType = (file) => {
  let { type } = file
  if (!type) {
    type = file.raw.type
  }
  return type || 'unknown'
}

/**
 * 保存图片到相册
 * @param picurl 需要下载的图片URL 支持图片文件（jpg/jpeg、png、bmp等格式）和视频文件（3gp、mov等格式）
 */
import { showToast } from 'vant'
const savePicture = (picurl) => {
  showToast({
    type: 'loading',
    message: '正在保存...',
    forbidClick: true,
    duration: 0,
    loadingType: 'spinner'
  })
  // eslint-disable-next-line no-undef
  const dtask = plus.downloader.createDownload(picurl, {}, function (d, status) {
    console.log('下载结果', d, status)
    // 下载完成
    if (status === 200) {
      // eslint-disable-next-line no-undef
      plus.gallery.save(
        picurl,
        function () {
          showToast('保存成功')
        },
        function (e) {
          console.log('保存失败，请重试！', e)
          showToast('保存失败，请重试！')
        }
      )
    } else {
      showToast('Download failed: ' + status)
    }
  })
  dtask.start()
}

export { getFileType, isImageType, getIconByFileType, downloadByBlob, savePicture }
